'use strict'

const path = require('path')

const mime = require('mime')
const fs = require('mz/fs')


function  staticFiles(url,dir){
    return async(ctx,next)=>{
        let rpath = ctx.request.path;
     
        if (rpath.startsWith(url)){
            let fp  = path.join(dir,rpath.substring(url.length));
            if (await fs.exists(fp)){
                ctx.response.type = mime.getType(rpath)
                ctx.response.body = await fs.readFile(fp)
            }else{
                   // 文件不存在:
                   ctx.response.status = 404;
            }
        }else{
                // 不是指定前缀的URL，继续处理下一个middleware:
                await next();
        }
    }
}

module.exports = staticFiles;